import {User} from "../sqlite/model/User";
import {StringUtil} from "../../utils/StringUtil";
import {UserResource} from "../sqlite/model/UserResource";
import {Lesson} from "../sqlite/model/Lesson";
import {Downloaded} from "../sqlite/model/Downloaded";

export class GenBookZip {

    constructor(){
        const fs = require('fs');
        const path = require('path')
        // this.requireBooks = ['1240973040711376897', '1240973040493273089', '1240973040551993346', '1240973040652656641']
        this.requireBook = '1240180248527511553';
        // this.dbFilePath = "C:\\Program Files (x86)\\美丽科学\\resources\\data\\novoedu.smd";
        this.dbFilePath = "D:\\bsc-client-electron\\data\\novoedu_test.smd";
        // this.resourcePath = "C:\\Program Files (x86)\\美丽科学\\resources\\data\\resc";
        this.resourcePath = "D:\\bsc-client-electron\\data\\resc";
        this.destPath = path.resolve("D:\\dest", this.requireBook);
        if(!fs.existsSync(this.destPath)){
            fs.mkdirSync(this.destPath)
        }
        this.sqlite = require('sqlite-sync');
    }

    generateBook(){
        const fs = require('fs');
        const path = require('path')
        let bookJson = this.queryOneBookResources(this.requireBook);
        let jsonPath = path.resolve(this.destPath, "description.json");
        fs.writeFileSync(jsonPath, JSON.stringify(bookJson));
    }

    queryOneBookResources(bookId){
        const path = require("path")
        const fs = require("fs");
        let bookJson = {};
        let user = this.getCurrentUser();
        let sql = StringUtil.format("SELECT * FROM t_user_resource WHERE user_id = '{0}'" +
            " AND lesson_id IN (SELECT id FROM t_lesson WHERE chapter_id IN ( SELECT id FROM t_chapter WHERE book_id = '{1}' ))", user.id, bookId);
        let result = this.runSql(sql);
        bookJson.resources = [];
        if(result[0]){
            let userResource = new UserResource();
            result.forEach(value => {
                userResource = userResource.mappingModel(value);
                bookJson.resources.push(userResource);
                if(userResource.resourceType === "PolyvVideo"){
                    let vid = JSON.parse(userResource.resourceDescription).vid;
                    let zipPath = path.resolve(this.resourcePath, userResource.resourceType, userResource.resourceId, "video", vid, userResource.resourceId + ".zip");
                    let m3u8AndkeyPath = path.resolve(this.resourcePath, userResource.resourceType, userResource.resourceId, "video", vid);
                    let typeDir = path.resolve(this.destPath,  userResource.resourceType);
                    if(!fs.existsSync(typeDir)){
                        fs.mkdirSync(typeDir);
                    }
                    typeDir = path.resolve(typeDir, userResource.resourceId);
                    if(!fs.existsSync(typeDir)){
                        fs.mkdirSync(typeDir);
                    }
                    typeDir = path.resolve(typeDir, "video");
                    if(!fs.existsSync(typeDir)){
                        fs.mkdirSync(typeDir);
                    }
                    typeDir = path.resolve(typeDir, vid);
                    if(!fs.existsSync(typeDir)){
                        fs.mkdirSync(typeDir);
                        let reg = /(.key)|(.m3u8)$/
                        const currVidArry = fs.readdirSync(m3u8AndkeyPath)
                        let m3u8AndKey = currVidArry.filter(v=>reg.test(v))
                        console.log(m3u8AndKey)
                        m3u8AndKey.forEach(v=>{
                            let resPath = path.resolve(m3u8AndkeyPath,v)
                            let targetPath = path.resolve(typeDir,v)
                            fs.copyFileSync(resPath,targetPath)
                            console.log(resPath+'->'+targetPath+'成功')
                        })
                    }
                    if(fs.existsSync(zipPath)){
                        fs.copyFileSync(zipPath, path.resolve(typeDir, userResource.resourceId + ".zip"))
                        this.copyThumb(userResource)
                    }
                } else if(userResource.resourceType === "courseware"){
                    let pptPath = path.resolve(this.resourcePath, userResource.resourceType, userResource.resourceId + ".ppt");
                    let typeDir = path.resolve(this.destPath, userResource.resourceType);
                    if(!fs.existsSync(typeDir)){
                        fs.mkdirSync(typeDir);
                    }
                    if(fs.existsSync(pptPath)){
                        this.copyThumb(userResource)
                        fs.copyFileSync(pptPath, path.resolve(typeDir, userResource.resourceId + ".ppt"))
                    }
                } else {
                    let zipPath = path.resolve(this.resourcePath, userResource.resourceType, userResource.resourceId + ".zip");
                    let typeDir = path.resolve(this.destPath, userResource.resourceType);
                    if(!fs.existsSync(typeDir)){
                        fs.mkdirSync(typeDir);
                    }
                    if(fs.existsSync(zipPath)){
                        this.copyThumb(userResource)
                        fs.copyFileSync(zipPath, path.resolve(typeDir, userResource.resourceId + ".zip"))
                    }
                }
            })
        }
        sql = StringUtil.format("SELECT * FROM t_lesson WHERE chapter_id IN ( SELECT id FROM t_chapter WHERE book_id = '{0}')", bookId);
        result = this.runSql(sql);
        bookJson.lessons = [];
        if(result[0]){
            let lesson = new Lesson();
            result.forEach(value => {
                bookJson.lessons.push(lesson.mappingModel(value));
            })
        }

        sql = StringUtil.format("SELECT * from t_download_complete where user_id = '{0}'", user.id);
        result = this.runSql(sql);
        bookJson.downloaded = [];
        if(result[0]){
            let downloaded = new Downloaded();
            result.forEach(value => {
                bookJson.downloaded.push(downloaded.mappingModel(value));
            })
        }
        return bookJson;
    }
    copyThumb(userResource){
        const path = require('path')
        const fs = require('fs')
        let thumpCopyDir = path.resolve(this.destPath, userResource.resourceType,userResource.resourceId,'thumb')
        let _path = path.resolve(this.resourcePath,userResource.resourceType, userResource.resourceId,'thumb')
        if(fs.existsSync(_path)){
            let idPath = path.resolve(this.destPath,userResource.resourceType, userResource.resourceId)
            console.log(idPath)
            console.log(fs.existsSync(idPath))
            if(!fs.existsSync(idPath)){
                fs.mkdirSync(idPath)
            }
            fs.copyFileSync(_path,thumpCopyDir)
        }
    }
    getCurrentUser(){
        let sql = "select * from t_user order by active_time desc limit 1"
        let result = this.runSql(sql);
        if (this.checkSqlError(result)) {
            if(result[0]){
                let temp = new User();
                return temp.mappingModel(result[0]);
            }else {
                return null;
            }
        } else {
            return result;
        }
    }

    checkSqlError(result) {
        if (result) {
            if (result === "sql error") {
                return false;
            }
            if (result === "param error") {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    runSql(sql) {
        this.sqlite.connect(this.dbFilePath);
        let result = this.sqlite.run(sql);
        this.sqlite.close();
        if (result.error) {
            console.log(result.error);
            return "sql error";
        }
        return result;
    }
}
